import { Controller } from 'egg';
const CryptoJS = require('crypto-js');
const moment = require('moment');
require('colors');

export default class AdminController extends Controller {

  private createRandom() {
    let rn = Math.random();
    // tslint:disable-next-line:binary-expression-operand-order
    return (9 * rn).toFixed()
  }

  /**
   * @api {get} admin/backLogin 后台管理员登录
   *  
   * @apiName backLogin
   * @apiGroup Admin
   * @apiDescription 后台管理员登录
   * 
   * @apiParam {String} [name] 用户名
   * @apiParam {String} [password] 密码
   * 
   */
  public async backLogin(ctx) {
    let { name, password } = ctx.request.body;
    try {
      if (name && password) {
        let md5_password = CryptoJS.MD5(password).toString();
        let result = await ctx.model.User.findOne({
          attributes: {
            exclude: ['password', 'createdAt', 'updatedAt'],
          },
          where: {
            name: name,
            password: md5_password
          }
        });
        if (!result) {
          throw ctx.helper.getErrorMsg(210);
        }
        let response_obj = {};
        let userRole = await ctx.model.Role.findOne({
          where: {
            role_Id: parseInt(result.dataValues.roleId)
          }
        });
        if (userRole.dataValues.limit.includes('backLogin')) {
          let token_json = {
            roleId: parseInt(result.dataValues.roleId),
            limit: userRole.dataValues.limit,
            name: result.dataValues.name,
            time: moment().format('YYYY-MM-DD HH:mm:ss')
          }
          let user_token = CryptoJS.AES.encrypt(JSON.stringify(token_json), 'sharesites');
          await this.app.redis.lpush('adminLoginMessage', user_token.toString());
          await this.app.redis.ltrim('adminLoginMessage', 0, 9);
          response_obj = {
            code: 200,
            data: {
              token: user_token.toString(),
            },
            status: '成功'
          }

        } else {
          response_obj = ctx.helper.getErrorMsg(204);
        }

        ctx.response.body = response_obj;
      } else {
        throw ctx.helper.getErrorMsg(211);
      }
    } catch (msg) {
      ctx.response.body = msg;
    }
  }

  /**
   * @api {get} admin/initBackLogin 初始化后台管理员
   *  
   * @apiName initBackLogin
   * @apiGroup Admin
   * @apiDescription 只有当后台管理员不存在的时候，初始化才能成功,初始化密码为123456
   * 
   */
  public async initBackLogin(ctx) {
    try {
      let findAdmin = await ctx.model.User.findOne({
        where: {
          name: 'admin'
        }
      });
      if (!Object.is(findAdmin, null)) {
        throw ctx.helper.getErrorMsg(200);
      }
      await ctx.model.Role.create({
        name: 'superAdmin',
        text: '超级管理员',
        limit: 'backLogin',
        roleId: 0
      });
      let md5_password = CryptoJS.MD5('123456').toString();
      await ctx.model.User.create({
        name: 'admin',
        password: md5_password
      });
      ctx.response.body = {
        code: 200,
        status: '用户创建成功'
      };
    } catch (error_info) {
      ctx.response.body = error_info;
    }

  }

  /**
   * @api {post} admin/forgetPassword 后台管理员忘记密码
   *
   * @apiName forgetPassword
   * @apiGroup Admin
   * @apiDescription 忘记密码，校验管理员身份并发送短信
   *
   * @apiParam {String} email 邮箱
   */
  public async forgetPassword(ctx) {
    try {
      const { email } = ctx.request.body;
      let newPwd = '';
      if (!email) {
        throw ctx.helper.getErrorMsg(227);
      }
      let user = await ctx.model.User.findOne({
        where: {
          email
        }
      })
      if (!user) {
        throw ctx.helper.getErrorMsg(211);
      }

      for (let i = 0; i < 6; i++) {
        newPwd = `${newPwd}${this.createRandom()}`
      }

      const { roleId } = user.dataValues;
      // ctx.logger.info('roleId: ', roleId);
      let userRole = await ctx.model.Role.findOne({
        where: {
          roleId
        }
      })
      // ctx.logger.info('userRole: ', userRole);
      if (!userRole.dataValues.limit.includes('backLogin')) {
        throw ctx.helper.getErrorMsg(204);
      }
      await ctx.model.User.update({
        password: CryptoJS.MD5(newPwd).toString()
      }, {
        where: {
          email
        }
      })
      await this.service.tools.email({
        revicer: email,
        title: '管理员修改密码',
        content: `随机密码为:${newPwd}`
      })
      ctx.response.body = {
        code: 200,
        status: '成功'
      }
    } catch (info) {
      ctx.response.body = info
    }

  }
}
